<script setup lang='ts'>
import { User, Lock, Message, Key } from '@element-plus/icons-vue';
import { reactive } from 'vue';
import { ref } from 'vue';
import useUserstore from '../../store/modules/user'
import { useRouter } from 'vue-router';
import { getTime } from '../../utils/time';
import { ElNotification } from 'element-plus'
import { reqCaptcha } from '../../apis/user';
import { onMounted } from 'vue';
import type { ElInput } from 'element-plus'



const usernameInput = ref<InstanceType<typeof ElInput>>()
const emailInput = ref<InstanceType<typeof ElInput>>()
const passwordInput = ref<InstanceType<typeof ElInput>>()
const captchaInput = ref<InstanceType<typeof ElInput>>()
let captchaSrc = ref<string>('')
const $router = useRouter()
const useUser = useUserstore()
const registerRef = ref()
const loading = ref<boolean>(false)
const registerDate = ref({
  username: '',
  password: '',
  email: '',
  captcha: ''
})

onMounted(() => {
  getCaptcha()
})
// 表单校验规则
const formRules = reactive({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    }
  ],
  captcha: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    }
  ]
})

const getCaptcha = async () => {
  // captchaSrc.value = 'http://172.21.160.134:8080/user/captcha?' + new Date().getTime()
  const res = await reqCaptcha()
  // console.log(res)
  captchaSrc.value = res
  // console.log('captcha',captchaSrc.value)
}

const handlerRegister = async () => {
  await registerRef.value.validate()
  loading.value = true
  try {
    await useUser.userRegister(registerDate.value)
    ElNotification({
      title: `Hi,${getTime()}好`,
      message: '注册成功',
      type: 'success',
    })
    loading.value = false
    $router.push('/login')
  } catch (error) {
    ElNotification.error((error as Error).message)
    handlerClean()
    getCaptcha()
    loading.value = false
  }
}

const handlerClean = () => {
  Object.assign(registerDate.value, {
    username: '',
    email: '',
    password: '',
    captcha: ''
  })
}

// 处理回车事件
const handleEnter = (field: string) => {
  const fieldsOrder = [emailInput, usernameInput, passwordInput, captchaInput]

  const currentIndex = fieldsOrder.findIndex(ref => ref === {
    username: usernameInput,
    email: emailInput,
    password: passwordInput,
    captcha: captchaInput
  }[field])

  if (currentIndex < fieldsOrder.length - 1) {
    fieldsOrder[currentIndex + 1]?.value?.focus()
  } else {
    handlerRegister()
  }
}

let backLogin = () => {
  $router.push('/login')
}
</script>


<template>
  <div class="login_container">
    <!-- 添加30个流星元素 -->
    <div v-for="n in 30" :key="n" class="meteor"></div>

    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :rules="formRules" ref="registerRef" :model="registerDate">
          <h1>Hello</h1>
          <h2>请注册您的TAPD账号</h2>
          <div class="form">
            <el-form-item prop="email">
              <el-input :prefix-icon="Message" v-model="registerDate.email" placeholder="请输入邮箱"
                @keydown.enter="handleEnter('email')" ref="emailInput" clearable /> </el-form-item>
            <el-form-item prop="username">
              <el-input :prefix-icon="User" v-model="registerDate.username" placeholder="请输入用户名"
                @keydown.enter="handleEnter('username')" ref="usernameInput" clearable /> </el-form-item>
            <el-form-item prop="password">
              <el-input :prefix-icon="Lock" v-model="registerDate.password" placeholder="请输入密码"
                @keydown.enter="handleEnter('password')" ref="passwordInput" type="password" show-password clearable />
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input :prefix-icon="Key" placeholder="请输入验证码" v-model="registerDate.captcha"
                @keydown.enter="handleEnter('captcha')" ref="captchaInput">
                <template #append>
                  <img :src="captchaSrc" alt="" style="width: 100px;height: 32px;" @click="getCaptcha">
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width: 30%;margin: 0 auto;" @click="handlerRegister"
                :loading="loading">下一步</el-button>
              <el-link type="primary" @click="backLogin">返回登陆</el-link>
            </el-form-item>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>


<style scoped lang='scss'>
@use "sass:math";

.login_container {
  width: 100%;
  height: 100vh;
  background: linear-gradient(to bottom, #0f2027, #203a43, #2c5364);
  position: relative;
  overflow: hidden;

  /* 垂直下落的流星效果 */
  .meteor {
    position: absolute;
    width: 4px;
    height: 4px;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0));
    border-radius: 50%;
    box-shadow: 0 0 15px 3px rgba(255, 255, 255, 0.9);
    animation: meteor 3s linear infinite;

    /* 流星尾部 */
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 2px;
      height: 120px;
      background: linear-gradient(to top, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0));
    }

    @for $i from 1 through 30 {
      &:nth-child(#{$i}) {
        top: -10px;
        left: math.random(100) + vw;
        animation-delay: math.random(20) + s;
        animation-duration: math.random(3) + 1 + s;
        opacity: math.div(math.random(100), 100) + 0.3;
      }
    }
  }

  @keyframes meteor {
    0% {
      transform: translateY(0) scale(1);
      opacity: 1;
    }

    70% {
      opacity: 0.8;
    }

    100% {
      transform: translateY(100vh) scale(0.5);
      opacity: 0;
    }
  }

  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background-color: rgba(20, 68, 105, 0.4);
    backdrop-filter: blur(5px);
    border-radius: 10px;
    padding: 40px;
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.2);

    h1 {
      color: #fff;
      font-size: 40px;
      text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
    }

    h2 {
      color: #fff;
      font-size: 20px;
      margin: 20px 0;
      text-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
    }

    .form {
      width: 80%;
      margin: auto;

      :deep(.el-input-group__append) {
        padding: 0;
        border: none;
        background: transparent;
        box-shadow: none;
      }
    }
  }
}
</style>